<template>
  <q-dialog v-model="datePopup">
    <div class="q-pa-md">
      <div class="q-gutter-md row items-start">
        <!-- <q-date
                        years-in-month-view
                          mask="YYYY/MM"
                          v-model="createForm.data.date_code"
                          minimal
                          @update:model-value="datePopup = false"
                        /> -->
        <DateCodeSelect @update="updateReplacementTime"></DateCodeSelect>
      </div>
    </div>
  </q-dialog>
  <q-dialog v-model="addDig">
    <OrderHardTimeForm
      :mode="'create'"
      :orderId="props.orderId"
      @close="addDig = false"
      @submit="initData()"
    >
    </OrderHardTimeForm>
  </q-dialog>
  <ScrollArea :bot-margin="50">
    <div>
      <q-card-actions align="right" v-if="!readOnly">
        <q-btn class="default-btn" @click="addDig = true"
          >Add Hard Time Replacement</q-btn
        >
      </q-card-actions>

      <div class="sub-header">Hard Time Replacement Task</div>
      <q-table
        :rows="parent"
        :columns="cols"
        :rows-per-page-options="[5]"
        :pagination="pagination"
        class="my-table"
        wrap-cells
      >
        <template v-slot:body-cell-description="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            <!-- {{ props.row.stock_item.stock_code }} -->
            {{ props.value }}
          </q-td>
        </template>

        <template v-slot:body-cell-serial_no="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{ props.row.serial_no }}
          </q-td>
        </template>
        <template v-slot:body-cell-component="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{ props.value }}
          </q-td>
        </template>
        <!-- <template v-slot:body-cell-replaced="props">
        <q-td :class="{
          'fail': (props.row.is_critical && props.row.complete==false) || (props.row?.diff == 0 && props.row.complete==false),
          'pass': props.row?.diff > 6 || props.row.complete,
          'warning': props.row?.diff <= 6&& props.row?.diff >3
        }" >
          <div class="row justify-start">
            {{ props.row.replaced != null ?  props.row.replaced.slice(0, 7):'' }}
          </div>
        </q-td>
      </template> -->
        <template v-slot:body-cell-last="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),
              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{
              props.row.last_replaced != null
                ? props.row.last_replaced.slice(0, 7)
                : ''
            }}
          </q-td>
        </template>

        <template v-slot:body-cell-next="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{
              props.row.next_replace != null
                ? props.row.next_replace.slice(0, 7)
                : ''
            }}

            <q-tooltip
              class="bg-indigo"
              :offset="[10, 10]"
              v-if="props.row.next_replace != null"
            >
              {{ checkDiff(props.row?.diff) }}
            </q-tooltip>
          </q-td>
        </template>

        <template v-slot:body-cell-period="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{ props.row.period }}
          </q-td>
        </template>

        <template v-slot:body-cell-actions="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            <q-checkbox
              :disable="readOnly"
              v-model="props.row.complete"
              @update:model-value="
                (val, evt) =>
                  updateReplacementComplete(
                    val,
                    evt,
                    props.row.id,
                    props.row.replaced
                  )
              "
            />
            <q-btn
              v-if="props.row.order_only"
              class="q-px-sm"
              color="negative"
              flat
              icon="delete"
              @click="deleteFn(props.row.id)"
            />
          </q-td>
        </template>

        <template v-slot:body-cell-update="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            <div style="max-width: 300px">
              <q-input
                hide-bottom-space
                borderless
                mask="####/##"
                readonly
                :model-value="formatDateTimeString(props.row.replaced)"
              >
                <template v-slot:append>
                  <q-icon
                    class="cursor-pointer"
                    size="md"
                    @click="openDateCode(props.row.id, props.row.complete)"
                  >
                    <img :src="dateIcon" />
                  </q-icon>
                </template>

                <!-- <template v-slot:append>
                  <q-icon name="event" class="cursor-pointer">
                    <q-popup-proxy cover>
                      <q-date v-model="date">
                        <div class="row items-center justify-end">
                          <q-btn
                            v-close-popup
                            label="Close"
                            color="primary"
                            flat
                          />

                          <q-btn
                            v-close-popup
                            label="Submit"
                            color="primary"
                            flat
                            :disable="readOnly"
                            @click="
                              updateReplacementTime(
                                dateCode,
                                props.row.id,
                                props.row.complete
                              )
                            "
                          />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </q-icon>
                </template> -->
              </q-input>
            </div>
          </q-td>
        </template>
      </q-table>

      <div class="sub-header" v-if="childs.length > 0">
        Childs Hard Time Replacement Task
      </div>
      <q-table
        v-if="childs.length > 0"
        :rows="childs"
        :columns="cols"
        :rows-per-page-options="[5]"
        class="my-table"
        :pagination="pagination"
        wrap-cells
      >
        <template v-slot:body-cell-description="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            <!-- {{ props.row.stock_item.stock_code }} -->
            {{ props.value }}
          </q-td>
        </template>

        <template v-slot:body-cell-last="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{
              props.row.last_replaced != null
                ? props.row.last_replaced.slice(0, 7)
                : ''
            }}
          </q-td>
        </template>

        <template v-slot:body-cell-next="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{
              props.row.next_replace != null
                ? props.row.next_replace.slice(0, 7)
                : ''
            }}
            <q-tooltip
              class="bg-indigo"
              :offset="[10, 10]"
              v-if="props.row.next_replace != null"
            >
              {{ checkDiff(props.row?.diff) }}
            </q-tooltip>
          </q-td>
        </template>

        <template v-slot:body-cell-serial_no="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{ props.row.serial_no }}
          </q-td>
        </template>

        <!-- <template v-slot:body-cell-replaced="props">
        <q-td :class="{
          'fail': (props.row.is_critical && props.row.complete==false) || (props.row?.diff == 0 && props.row.complete==false),
          'pass': props.row?.diff > 6 || props.row.complete,
          'warning': props.row?.diff <= 6&& props.row?.diff >3
        }">
          <div class="row justify-start">
            {{ props.row.replaced != null ?  props.row.replaced.slice(0, 7):'' }}
          </div>
        </q-td>
      </template> -->

        <template v-slot:body-cell-period="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{ props.row.period }}
          </q-td>
        </template>

        <template v-slot:body-cell-actions="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            <q-checkbox
              :disable="readOnly"
              v-model="props.row.complete"
              @update:model-value="
                (val, evt) =>
                  updateReplacementComplete(
                    val,
                    evt,
                    props.row.id,
                    props.row.replaced
                  )
              "
            />
            <q-btn
              v-if="props.row.order_only"
              class="q-px-sm"
              color="negative"
              flat
              icon="delete"
              @click="deleteFn(props.row.id)"
            />
          </q-td>
        </template>
        <template v-slot:body-cell-component="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            {{ props.value }}
          </q-td>
        </template>

        <template v-slot:body-cell-update="props">
          <q-td
            :class="{
              fail:
                (props.row.is_critical && props.row.complete == false) ||
                (props.row?.diff == 0 && props.row.complete == false),

              warning:
                props.row?.diff <= 6 &&
                props.row?.diff > 3 &&
                props.row.complete == false,
            }"
          >
            <div style="max-width: 300px">
              <q-input
                hide-bottom-space
                borderless
                mask="####/##"
                readonly
                :model-value="formatDateTimeString(props.row.replaced)"
              >
                <template v-slot:append>
                  <q-icon
                    class="cursor-pointer"
                    size="md"
                    @click="openDateCode(props.row.id, props.row.complete)"
                  >
                    <img :src="dateIcon" />
                  </q-icon>
                </template>
                <!-- <q-dialog v-model="datePopup">
                  <div class="q-pa-md">
                    <div class="q-gutter-md row items-start">
              
                      <DateCodeSelect
                        @update="updateReplacementTime"
                      ></DateCodeSelect>
                    </div>
                  </div>
                </q-dialog> -->
                <!-- <template v-slot:append>
                  <q-icon name="event" class="cursor-pointer">
                    <q-popup-proxy cover>
                      <q-date v-model="date">
                        <div class="row items-center justify-end">
                          <q-btn
                            v-close-popup
                            label="Close"
                            color="primary"
                            flat
                          />
                        
                          <q-btn
                            v-close-popup
                            label="Submit"
                            color="primary"
                            flat
                            :disable="readOnly"
                            @click="
                              updateReplacementTime(
                                props.row.id,
                                props.row.complete
                              )
                            "
                          />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </q-icon>
                </template> -->
              </q-input>
            </div>
          </q-td>
        </template>
      </q-table>
    </div>
  </ScrollArea>
</template>
<script setup lang="ts">
import { useQuasar } from 'quasar';
import { OrderHTReplacement } from 'src/services/type';
import { onMounted, ref } from 'vue';
import { deleteStockItemHtreplace } from 'src/services/repairService';
import OrderHardTimeForm from 'src/components/htReplacement/OrderHardTimeForm.vue';
import {
  getOrderHardTimeReplacement,
  updateReplacementTask,
} from 'src/services/repairService';
import { checkDiff } from 'src/utils/getPublic';
import ScrollArea from '../ScrollArea.vue';
import { formatDateBySlash, formatDateTimeString } from 'src/utils/dateUtils';
import dateIcon from 'src/assets/style/date.png';
import DateCodeSelect from 'src/components/DateCodeSelect.vue';

const emit = defineEmits(['update']);
const props = defineProps<{
  orderId: number;
  stockCode: string;
  orderPartId: number;
  isReadOnly: boolean;
}>();

const $q = useQuasar();
const id = ref(0);
const complete = ref(false);
const addDig = ref(false);
const editDiag = ref(false);

const datePopup = ref(false);

const readOnly = ref(false);
if (props.isReadOnly) {
  readOnly.value = true;
}

const parent = ref<OrderHTReplacement[]>([]);
const childs = ref<OrderHTReplacement[]>([]);
const align = 'left';

const pagination = {
  sortBy: 'component',
};
const cols = [
  {
    name: 'description',
    label: 'Short Description',
    field: 'description',
    align,
  },
  {
    name: 'serial_no',
    label: 'Serial No',
    field: 'serial_no',
    sortable: true,
    align,
  },
  {
    name: 'component',
    label: 'Component',
    field: 'component',
    sortable: true,
    align,
  },

  /*  {
    name: 'last',
    label: 'Last',
    field: 'last_replaced',
    sortable: true,
    align,
  }, */
  {
    name: 'next',
    label: 'Next ',
    field: 'next_replace',
    sortable: true,
    align,
  },
  // {
  //   name: 'replaced',
  //   label: 'ReplaceTime',
  //   field: 'replaced',
  //   sortable: true,
  //   align,
  // },
  {
    name: 'period',
    label: 'Period (Months)',
    field: 'period',
    sortable: true,
    align,
  },
  {
    name: 'update',
    label: 'Replaced Time',
    field: 'update',
    sortable: true,
    align,
  },
  {
    name: 'actions',
    label: 'Action',
    field: 'actions',
    sortable: true,
    align,
  },
];

const date = ref('');

const dateCode = ref('');

const month = new Date().getMonth().toString();
const year = new Date().getFullYear().toString();
date.value = year + '/' + month;

async function getOrderHardTimeReplacementData() {
  if (props.orderId) {
    const res = await getOrderHardTimeReplacement(props.orderId);
    if (res.data) {
      console.log(res.data);

      parent.value = res.data.filter(
        (item) => item.stock_code == props.stockCode
      );
      childs.value = res.data.filter(
        (item) => item.stock_code != props.stockCode
      );
    }
  }
}

function openDateCode(htId: number, completed: boolean) {
  if (readOnly.value) {
    return;
  }
  id.value = htId;
  complete.value = completed;
  datePopup.value = true;
}

async function updateReplacementTime(dateCode: string) {
  const res = await updateReplacementTask(id.value, complete.value, dateCode);

  if (res.data) {
    initData();
    emit('update');
    datePopup.value = false;
    $q.notify({
      message: 'success',
      color: 'positive',
    });
  }
}

async function updateReplacementComplete(
  val: boolean,
  evt: unknown,
  id: number,
  replaced: string
) {
  if (!replaced) {
    dateCode.value = date.value;
  }
  if (replaced) {
    dateCode.value = replaced.slice(0, 7);
  }
  console.log(val);

  const res = await updateReplacementTask(id, val, dateCode.value);
  if (res.data) {
    initData();
    emit('update');
    datePopup.value = false;
    $q.notify({
      message: 'success',
      color: 'positive',
    });
  }
}

function editFn(sie_id: number) {
  id.value = sie_id;
  editDiag.value = true;
}
function deleteFn(id: number) {
  $q.dialog({
    title: 'Confirm',
    message: 'Are you sure to delete this record?',
    cancel: true,
  }).onOk(async () => {
    const res = await deleteStockItemHtreplace(id);
    if (res) {
      initData();
    }
  });
}
async function initData() {
  /* const res = await getPartHardTimeReplacement(props.stockCode) */
  getOrderHardTimeReplacementData();
}
onMounted(() => {
  initData();
});
</script>
